Encuesta Intercensal 2015

La Encuesta Intercensal se guarda en un un archivo .RData.

data <- read_sav("~/Persona.-Encuesta Intercensal 2015.sav")
#data <- data %>%
 #        select(., c(1:96)) %>%
  #        select(-"filter_$")
save(data, 
      file = paste0(here::here(), "/Bases/Encuesta Intercensal_2015.RData"))

Se seleccionan las variables que se desean conservar para la realización de este documento y se guarda en un archivo .RData para practicidad del manejo de datos.

load(paste0(here::here(), "/Bases/Encuesta Intercensal_2015.RData"))

mydata <- data %>%
           select(CVE_ENT, NOM_ENT, MUN, NOM_MUN, ENT_MUN, ENT_PAIS_NAC, ENT_PAIS_RES10, ENT_MUN_RES_2010,
                  ENT_PAIS_TRAB, MUN_TRAB, ENT_MUN_TRAB, ENT_PAIS_ASI, MUN_ASI, ENT_MUN_ASI_ESC,
                  EDAD, SEXO, AFRODES, HLENGUA, QDIALECT_INALI, PERTE_INDIGENA, ALFABET, SITUA_CONYUGAL, 
                  HIJOS_NAC_VIVOS, CONACT, OCUPACION_C, SITUACION_TRAB, VACACIONES, SERVICIO_MEDICO, INCAP_SUELDO, 
                  INGTRMEN, ACTIVIDADES_C, TIE_TRASLADO_TRAB,  MED_TRASLADO_TRAB1, MED_TRASLADO_TRAB2, MED_TRASLADO_TRAB3, 
                  ASISTEN, NIVACAD, ESCOLARI, ESCOACUM, TIE_TRASLADO_ESCU, MED_TRASLADO_ESC1, MED_TRASLADO_ESC2, 
                  MED_TRASLADO_ESC3, FACTOR, ESTRATO, UPM) %>%
            rename("CVE_MUN" = "ENT_MUN",
                   "CVE_MUN_ASI" = "ENT_MUN_ASI_ESC",
                   "CVE_MUN_TRABAJO" = "ENT_MUN_TRAB",
                   "CVE_MUN_RES" = "ENT_MUN_RES_2010")

Zonas Metropolitanas 2015

Se anexa la base de datos de las Zonas Metropolitanas 2015 a la base orginal

ZM_2015 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2015.xlsx"), sheet = "ZM_2015") %>%
            select(CVE_ENT, CVE_MUN, CVE_ZM, NOM_ZM) %>%
             mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                    CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Se asignan las claves de las zonas metropolitanas de acuerdo a las diferentes variables de interes:

  • Residencia hace 5 años

  • Laboral

  • Estudiantil

mydata <- mydata %>%
           # Zonas Metropolitanas por residenicia
           left_join(., ZM_2015 %>% select(-CVE_ENT), by = c("CVE_MUN")) %>%
            # Zonas Metropolitanas en el lugar de residencia hace 5 años
            left_join(., ZM_2015 %>% select(-CVE_ENT) %>% 
                           rename("CVE_ZM_RES" = "CVE_ZM",
                                  "ZM_RES" = "NOM_ZM"), by = c("CVE_MUN_RES" = "CVE_MUN")) %>%
             # Zonas Metropolitanas en el lugar de trabajo
             left_join(., ZM_2015 %>% select(-CVE_ENT) %>% 
                             rename("CVE_ZM_TRABAJO" = "CVE_ZM",
                                    "ZM_TRABAJO" = "NOM_ZM"), by = c("CVE_MUN_TRABAJO" = "CVE_MUN")) %>%
              # Zonas Metropolitanas en el lugar de estudio
              left_join(., ZM_2015 %>% select(-CVE_ENT) %>% 
                            rename("CVE_ZM_ASI" = "CVE_ZM",
                                   "ZM_ASI" = "NOM_ZM"), by = c("CVE_MUN_ASI" = "CVE_MUN"))

save(mydata, file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2015.RData"))          

✔️A partir de aquí se pueden correr los códidos 👇. Se carga el archivo Migracion por Zonas Metropolitanas_2015.RData.

load(file = paste0(here::here(), "/Bases/06_Migracion por Zonas Metropolitanas_2015.RData"))

# Para fines prácticos se genera un ponderador de uno 
mydata <- mydata %>%
           select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI, 
                  EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
            mutate(M = 1) 

# Se vuelve a cargar la base de datos para fines practicos
ZM_2015 <- read.xlsx(paste0(here::here(), "/Bases/Municipio/ZM_2015.xlsx"), sheet = "ZM_2015") %>%
            mutate(CVE_ENT = stringr::str_pad(.$CVE_ENT, width = 3, side = c("left"), pad = "0"),
                   CVE_MUN = stringr::str_pad(.$CVE_MUN, width = 6, side = c("left"), pad = "0"))

Entidades y Municipios

Se genera un vector con el nombre de las entidades llamado estados para facilitar los filtros en el documento.
Se genera un vector con las abreviaturas de las entidades llamado ent para fines prácticos.
Se genera un vector con las claves de los municipios, pero es importante hacer notar que tres municipios no entraron el muestreo del Cuestionario Ampliado.

# Claves de los estados
estados <- sjlabelled::get_labels(mydata$CVE_ENT)
nom_estados <- c( "Aguascalientes", "Baja California" ,"Baja California Sur", "Campeche", "Coahuila de Zaragoza", "Colima", 
                  "Chiapas", "Chihuahua", "Ciudad de México", "Durango", "Guanajuato", "Guerrero", "Hidalgo", "Jalisco",        
                  "México", "Michoacán de Ocampo", "Morelos", "Nayarit", "Nuevo León", "Oaxaca", "Puebla", "Querétaro", 
                  "Quintana Roo", "San Luis Potosí", "Sinaloa", "Sonora", "Tabasco", "Tamaulipas", "Tlaxcala", 
                  "Veracruz de Ignacio de la Llave", "Yucatán", "Zacatecas")
est <- c("AGS", "BC", "BCS", "CAMP", "COAH", "COL", "CHIS", "CHIH", "CDMX", "DGO", "GTO", "GRO", "HGO",
         "JAL", "MEX", "MICH", "MOR", "NAY", "NL", "OAX", "PUE", "QRO", "QROO", "SLP","SIN","SON", "TAB", 
         "TAMS", "TLX", "VER", "YUC", "ZAC")

# Claves de los municipios
MUN <- readRDS(paste0(here::here(), "/Bases/municipios_2015.RDS"))
nom_municipios <- sjlabelled::get_labels(MUN$NOM_MUN) %>% as.factor()
municipios <- sjlabelled::get_labels(MUN$CVE_MUN) %>% as.factor()
#saveRDS(MUN, file = paste0(here::here(), "/Bases/municipios_2015.RDS"))

# Claves de las zonas metropolitanas
zm <- sjlabelled::get_labels(mydata$CVE_ZM)[-2]
nom_zm <- sjlabelled::get_labels(mydata$NOM_ZM)[-2]

Movilidad estudiantil

Movilidad interna

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2015 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2015 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_municipal.RDS"))

Matrices

Se genera una matriz cruzada de la movilidad estudiantil a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_municipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Municipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil a nivel municipal, 2015.

Matriz de movilidad estudiantil a nivel municipal
Zonas Metropolitanas
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 255198 64 0 0 911 239 160 52 0 260 23 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 386 12336 0 0 0 90 100 0 15 130 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 275 0 14507 0 8 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 170 0 0 4350 0 10 249 0 12 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7450 0 52 7 29606 33 132 0 0 8 253 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 769 0 0 0 25 12872 426 32 13 0 614 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 538 0 0 42 10 205 15734 82 103 0 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 141 0 0 0 0 69 58 2473 0 0 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 123 33 0 4 2 104 324 0 5660 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 217 24 2 0 0 2 0 0 2 5563 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 1404 25 2 3 334 165 146 13 4 3 11843 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 134903 115 5 25 29 0 0 0 0 0 0 2 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 104 272371 0 17 39 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 10 74 28999 1014 20 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 241 27 290 439862 2269 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 38 16 29 1937 24485 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 16 6 0 0 0 19614 0 153 6 30 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 98 5 0 5 0 0 13157 12 0 8 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 6 2 0 0 0 11 0 73603 97 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 0 0 0 173 74639 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 40 0 20 2 4866 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15197 297 24 4 106 16 0 4
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 88 79728 98 78 9 71 0 6
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 102 64232 35 0 0 42 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 983 80 23452 0 10 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 210 362 34 2 8117 6 0 22
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 254 0 3 3 9594 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 33 0 0 0 2373 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30 213 2 1 51 8 0 2605
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 178 48 53 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2015 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2015 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2015 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 
#### Filtro de estados <<<<< filter(value >= 100000000000) %>% 
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios,
#                filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel municipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
################################################################################
tabla1 <- migration_flows_metropolitan(tabla = Migrantes, 
                                       filtro_zm = ZM, 
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       Emigrantes = Emigrantes, 
                                       Inmigrantes = Inmigrantes, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group = "Otros estados")

## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/4) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#                              }
 #                                          
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio", 
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio", 
                                  Emigrantes = "%Entran por estudio") 

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel municipal_Reduccion_Totales.xlsx"), 
                   overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel municipal.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (municipal).pdf"

## Gráficos a nivel municipal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.2,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = c(0, 0, 0, 0))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZM a nivel municipal.pdf"

## Etiquetas a nivel municipal 
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2015 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2015 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (municipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 18000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 6000) %>% 
                      pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = filtro_est, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "Otros estados") %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 
# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (municipal).pdf"

## Gráficos a nivel municipal (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.25,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.15, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 3, 
                    clock.wise = TRUE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 30)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value > 18000) %>% 
               pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value >= 6000) %>% 
                      pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = filtro_est, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "Otros estados") 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()
# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()
# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                        fill = "-", 
                        na.rm = TRUE, 
                        ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel municipal_Reduccion.xlsx"), 
               overwrite = TRUE)
tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (municipal).pdf"

## Gráficos a nivel municipal (ZMVM)
chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.25,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = TRUE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15, 
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20, 
                         group4 = grupo4, 
                         group4.text = "Otro municipios",
                         group4.col = 30)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZMVM a nivel municipal.pdf"

## Etiquetas a nivel municipal (ZMVM)
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)

#########################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 50), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 50) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.7,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (municipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (municipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (municipal).RData"))
Indicadores de movilidad estudiantil a nivel municipal
Zonas Metropolitanas
CVE_MUN Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 877 190 830 111 255 198 2 697 14 454 −11 757 17 151 0.63 3.386 −2.8 −28 908
001002 46 464 43 572 12 336 1 057 404 653 1 461 4.70 1.795 2.9 −808
001003 56 048 52 522 14 507 314 135 179 449 1.16 0.497 0.7 −270
001004 15 577 14 587 4 350 487 214 273 701 6.46 2.838 3.6 −428
001005 120 405 112 668 29 606 7 956 1 290 6 666 9 246 13.65 2.214 11.4 −2 580
001006 46 473 43 452 12 872 1 932 930 1 002 2 862 8.59 4.137 4.5 −1 860
001007 53 866 50 295 15 734 1 047 1 819 −772 2 866 4.02 6.985 −3.0 −3 638
001008 8 896 8 248 2 473 310 181 129 491 7.23 4.223 3.0 −362
001009 20 926 19 549 5 660 614 149 465 763 6.07 1.473 4.6 −298
001010 20 245 18 921 5 563 257 444 −187 701 2.62 4.535 −1.9 −888
001011 46 454 43 109 11 843 2 111 935 1 176 3 046 9.43 4.176 5.3 −1 870
002001 486 639 462 140 134 903 249 674 −425 923 0.10 0.284 −0.2 −1 348
002002 988 417 941 669 272 371 388 1 556 −1 168 1 944 0.08 0.322 −0.2 −3 112
002003 102 406 97 355 28 999 1 118 339 779 1 457 2.24 0.679 1.6 −678
002004 1 641 570 1 559 361 439 862 2 885 3 127 −242 6 012 0.36 0.391 0.0 −6 254
002005 96 734 91 779 24 485 2 024 2 357 −333 4 381 4.29 5.001 −0.7 −4 714
003001 72 564 69 201 19 614 229 51 178 280 0.65 0.144 0.5 −102
003002 60 171 56 803 13 157 139 0 139 139 0.48 0.000 0.5 0
003003 272 711 260 109 73 603 147 441 −294 588 0.11 0.331 −0.2 −882
003008 287 671 271 544 74 639 297 114 183 411 0.21 0.082 0.1 −228
Fuente: Estimaciones del CONAPO.

Movilidad intramunicipal

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2015 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2015 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_intramunicipal.RDS"))

Matrices

Se genera una matriz cruzada de la movilidad estudiantil a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_intramunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intramunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil a nivel municipal, 2015.

Matriz de movilidad estudiantil a nivel intramunicipal
Zonas Metropolitanas
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003002 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008
001001 255198 0 0 0 911 0 0 0 0 0 23 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 0 12336 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 0 0 14507 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 0 0 0 4350 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 7450 0 0 0 29606 0 0 0 0 0 253 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 0 0 0 0 0 12872 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 0 0 0 0 0 0 15734 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 0 0 0 0 0 0 0 2473 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 0 0 0 0 0 0 0 0 5660 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 0 0 0 0 0 0 0 0 0 5563 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 1404 0 0 0 334 0 0 0 0 0 11843 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 134903 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 0 272371 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 0 0 28999 1014 20 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 0 0 290 439862 2269 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 0 0 29 1937 24485 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 19614 0 0 0 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 13157 0 0 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 73603 0 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 74639 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4866 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 15197 0 0 0 0 0 0 0
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 79728 0 0 0 0 0 0
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 64232 0 0 0 0 0
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 23452 0 0 0 0
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8117 0 0 0
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9594 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2373 0
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2605
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Matrices por zonas metropolitanas

MR <- NULL
for(i in 1:length(zm)){
tabla <- ZM_2015 %>%
          select(CVE_ZM, CVE_MUN) %>%
           filter(CVE_ZM %in% zm[i]) %>%
            pull(CVE_MUN)

MR[[paste0(zm[i])]] <- Migrantes %>%
                        as.data.frame() %>%
                         tibble::rownames_to_column(var = "CVE_MUN") %>%
                          mutate_if(is.numeric, as.numeric) %>%
                           select(CVE_MUN, all_of(tabla)) %>%
                            filter(CVE_MUN %in% tabla)
}

# Se guardan en un objeto de R 
saveRDS(MR, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2015.RDS"))

# Se genera un Excel con todas las matrices por ZM
wb <- createWorkbook()
for(i in 1:length(zm)){
addWorksheet(wb, paste0(zm[i]))
writeData(wb, i, MR[[paste0(zm[i])]] %>% as.data.frame())
saveWorkbook(wb, 
              file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2015.xlsx"), 
               overwrite = TRUE)
}

Matriz de Movilidad estudiantil en la Zona Metropolitana de Cuernavaca, 2015.

Matriz de Movilidad estudiantil a nivel intramunicipal
Zona Metropolitana de Cuernavaca
CVE_MUN 017007 017008 017009 017011 017018 017020 017024 017028
017007 89359 479 46 1026 362 84 7 291
017008 4299 19295 0 1937 946 6 34 381
017009 1139 6 3840 10 12 0 0 4
017011 11939 1270 0 43292 570 4 0 115
017018 3892 697 0 217 23756 0 0 1242
017020 2591 46 18 2054 21 6961 0 17
017024 465 62 0 13 13 0 9637 42
017028 1583 485 0 84 1781 0 122 13398
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2015 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 3) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2015 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2015 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################# Filtro #########################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value < 0) %>% 

#p <- data.frame(ZM = ZM_CF,
 #               filtro_municipio = filtro_mig)

#write.table(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel intramunicipal.txt"), col.names = TRUE)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel intramunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel intramunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

################################################################################
tabla1 <- intramunicipal_flows_metropolitan(filtro_zm = ZM, 
                                            filtro_mig = filtro_mig, 
                                            Emigrantes = Emigrantes,
                                            Inmigrantes = Inmigrantes, 
                                            category_group = estados, 
                                            group = "Otros municipios")
tabla1 <- purrr::map(tabla1, ~ .x %>%
           dcast(rn ~ cn, value.var = "value", sum, na.rm = TRUE) %>%
            column_to_rownames(var = "rn"))

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                                             tabla1[[i]] %>%
#                                              as.data.frame() %>%
#                                               adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/50) %>%
#                                                    pull(Total)
#})

## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     if(i %in% 10) {
       tabla <- tabla1[[i]]
        } else {
        tabla <- tabla1[[i]] %>%
                  as.data.frame() %>%
                   adorn_totals(c("row", "col"), 
                                fill = "-", 
                                na.rm = TRUE, 
                                ,,,,contains(colnames(tabla1[[i]])))
        }           
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio", 
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio", 
                                  Emigrantes = "%Entran por estudio") 

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel intramunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel intramunicipal.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (Intramunicipal).pdf"

## Gráficos a nivel intramunicipal 
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZM a nivel intramunicipal.pdf"

## Etiquetas a nivel intramunicipal 
labels_chord_diagram(file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2015 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") 

tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2015 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      filter(value > 0) 
  }
)
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
               ggplot(aes(axis1 = rn, 
                           axis2 = cn, 
                            y = value),  # c("value", "freq", "tasa")
                       reverse = FALSE, 
                        na.rm = TRUE) +
                geom_alluvium(aes(fill = rn),
                               curve_type = "quintic", 
                                color = "transparent", 
                                 alpha = 0.85, 
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                  geom_stratum(aes(fill = cn), 
                                color = "white", 
                                 alpha = 0.65,  
                                  lwd = 0.001, 
                                   width = 1/5,
                                    reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3, 
                                      direction = "y", 
                                       nudge_x = -.2,
                                        min.segment.length = unit(1, "lines"),
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                    geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                     stat = "stratum", 
                                      size = 3,
                                       direction = "y", 
                                        nudge_x = .2, 
                                         force = 1,
                                          force_pull = 0,
                                           family = "montserrat",
                                            reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (Intramunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 13000) %>% 
               pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = NULL, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "ZMVM") %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%                        
            column_to_rownames(., var = "rn")   
# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (Intramunicipal).pdf"

## Gráficos a nivel intramunicipal (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.25,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = TRUE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
              filter(value < 13000) %>% 
               pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = NULL, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "ZMVM") 
tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()
# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
          ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel intramunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (Intramunicipal).pdf"

## Grafico a nivel intramunicipal (ZMVM)
chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.25,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = TRUE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15,
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 30)

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZMVM a nivel intramunicipal.pdf"

## Etiquetas a nivel intramunicipal (ZMVM)
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)     

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(value < 30000) %>% 
               pull(rn)

#########################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = ifelse(.$rn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$rn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$rn), 1, 3))], ")"), 50), .$rn),
                      cn = ifelse(.$cn %in% filtro, stringr::str_wrap(paste0(substr(as.character(.$cn), 1, 3), " Otros municipios(", estados[as.numeric(substr(as.character(.$cn), 1, 3))], ")"), 50) , .$cn)) %>%
                filter(value > 0) 

p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.7,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (Intramunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intramunicipal 2015.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar 
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intramunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intramunicipal).RData"))
Indicadores de movilidad estudiantil a nivel intramunicipal
Zonas Metropolitanas
CVE_MUN Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
001001 877 190 830 111 255 198 934 8 854 −7 920 9 788 0.22 2.07 −1.9 −17 708
001002 46 464 43 572 12 336 0 0 0 0 0.00 0.00 0.0 0
001003 56 048 52 522 14 507 0 0 0 0 0.00 0.00 0.0 0
001004 15 577 14 587 4 350 0 0 0 0 0.00 0.00 0.0 0
001005 120 405 112 668 29 606 7 703 1 245 6 458 8 948 13.22 2.14 11.1 −2 490
001006 46 473 43 452 12 872 0 0 0 0 0.00 0.00 0.0 0
001007 53 866 50 295 15 734 0 0 0 0 0.00 0.00 0.0 0
001008 8 896 8 248 2 473 0 0 0 0 0.00 0.00 0.0 0
001009 20 926 19 549 5 660 0 0 0 0 0.00 0.00 0.0 0
001010 20 245 18 921 5 563 0 0 0 0 0.00 0.00 0.0 0
001011 46 454 43 109 11 843 1 738 276 1 462 2 014 7.76 1.23 6.5 −552
002001 486 639 462 140 134 903 0 0 0 0 0.00 0.00 0.0 0
002002 988 417 941 669 272 371 0 0 0 0 0.00 0.00 0.0 0
002003 102 406 97 355 28 999 1 034 319 715 1 353 2.07 0.64 1.4 −638
002004 1 641 570 1 559 361 439 862 2 559 2 951 −392 5 510 0.32 0.37 0.0 −5 902
002005 96 734 91 779 24 485 1 966 2 289 −323 4 255 4.17 4.86 −0.7 −4 578
003001 72 564 69 201 19 614 0 0 0 0 0.00 0.00 0.0 0
003002 60 171 56 803 13 157 0 0 0 0 0.00 0.00 0.0 0
003003 272 711 260 109 73 603 0 0 0 0 0.00 0.00 0.0 0
003008 287 671 271 544 74 639 0 0 0 0 0.00 0.00 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermunicipal

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2015 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2015 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_intermunicipal.RDS"))

Matrices

Se genera una matriz cruzada de la movilidad estudiantil a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_intermunicipal.RDS"))

Migrantes <- svytable(~CVE_MUN_ASI + CVE_MUN, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_MUN, CVE_MUN_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_MUN" = "row_labels") %>% 
                  arrange(CVE_MUN) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_MUN = substr(.$CVE_MUN, 9, 17)) %>% 
              pull(CVE_MUN)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_MUN" = ".") %>%
                mutate(`CVE_MUN` = substr(.$CVE_MUN, 13, 18)) %>%
                 pull(CVE_MUN)

# Se elimina la variable CVE_MUN
Migrantes <- Migrantes %>%
              select(-CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Intermunicipal")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_MUN"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil a nivel municipal, 2015.

Matriz de movilidad estudiantil a nivel intermunicipal
Zonas Metropolitanas
CVE_MUN 001001 001002 001003 001004 001005 001006 001007 001008 001009 001010 001011 002001 002002 002003 002004 002005 003001 003003 003008 003009 004001 004002 004003 004004 004005 004006 004007 004008 004009
001001 0 64 0 0 0 239 160 52 0 260 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001002 386 0 0 0 0 90 100 0 15 130 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001003 275 0 0 0 8 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001004 170 0 0 0 0 10 249 0 12 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001005 0 0 52 7 0 33 132 0 0 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001006 769 0 0 0 25 0 426 32 13 0 614 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001007 538 0 0 42 10 205 0 82 103 0 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001008 141 0 0 0 0 69 58 0 0 0 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001009 123 33 0 4 2 104 324 0 0 0 9 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001010 217 24 2 0 0 2 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
001011 0 25 2 3 0 165 146 13 4 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002001 0 0 0 0 0 0 0 0 0 0 0 0 115 5 25 29 0 0 0 0 0 2 0 0 0 0 0 0 0
002002 0 0 0 0 0 0 0 0 0 0 0 104 0 0 17 39 0 0 0 0 0 0 0 0 0 0 0 0 0
002003 0 0 0 0 0 0 0 0 0 0 0 10 74 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002004 0 0 0 0 0 0 0 0 0 0 0 241 27 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
002005 0 0 0 0 0 0 0 0 0 0 0 38 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
003001 0 0 0 0 0 0 0 0 0 0 0 16 6 0 0 0 0 153 6 30 0 0 0 0 0 0 0 0 0
003002 0 0 0 0 0 0 0 0 0 0 0 98 5 0 5 0 0 12 0 8 0 0 0 0 0 0 0 0 0
003003 0 0 0 0 0 0 0 0 0 0 0 6 2 0 0 0 11 0 97 0 0 0 0 0 0 0 0 0 0
003008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 27 0 0 173 0 0 0 0 0 0 0 0 0 0 0
003009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 40 20 2 0 0 0 0 0 0 0 0 0 0
004001 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 297 24 4 106 16 0 4 20
004002 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 88 0 98 78 9 71 0 6 46
004003 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 45 102 0 35 0 0 42 0 42
004004 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 983 80 0 0 10 0 0 88
004005 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 210 362 34 2 0 6 0 22 6
004006 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 254 0 3 3 0 0 0 0
004007 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 33 0 0 0 0 0 1
004008 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30 213 2 1 51 8 0 0 0
004009 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 178 48 53 0 0 0 0 0
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

## Tomamos las Zonas Metropolitanas con más de 3 municipios que tienen flujos migratorios 
#### Con filtro (CF)
ZM_CF <- ZM_2015 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count >= 0) %>%
             pull(CVE_ZM)

NOM_ZM_CF <- ZM_2015 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

ZM <- lapply(1:length(ZM_CF), function(x){
                    ZM_2015 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% ZM_CF[x])  %>% 
                       mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 100)) %>% 
                        pull(NOM_MUN)
})

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
### Sacar el promedio de los flujos migratiorios para determinar como se van a grupar los estados 
#### Es importante correr la tabla1[[x]] sin filtros para determinar el número promedio de flujos de migración
#### Filtro <<<<< filter(value > 0) %>%
#p <- data.frame(ZM = ZM_CF,
#                filtro_municipio = tabla_municipios,
#                filtro_estado = tabla_estados)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_municipio)

#### Filtro de estados 
filtro_out <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel intermunicipal.xlsx"), colNames = TRUE) %>%
               pull(filtro_estado)

################################################################################
tabla1 <- migration_flows_metropolitan(tabla = Migrantes, 
                                       filtro_zm = ZM, 
                                       filtro_mig = filtro_mig, 
                                       filtro_out = filtro_out, 
                                       Emigrantes = Emigrantes, 
                                       Inmigrantes = Inmigrantes, 
                                       category_group = estados, 
                                       category_names = nom_estados,
                                       group = "Otros estados")

################################################################################
## Se sacan los flujos migratorios que pertencen a otros estados
#tabla_estados <- sapply(1:length(ZM_CF), function(i){
#                                           tabla1[[i]] %>%
#                                            as.data.frame() %>%
#                                             adorn_totals(c("row", "col"), 
#                                                           fill = "-", 
#                                                            na.rm = TRUE, 
#                                                             ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                              select(`Otros estados`) %>%
#                                               slice(nrow(.)) %>%
#                                                mutate(`Otros estados` = .$`Otros estados`/10) %>%
#                                                 pull(`Otros estados`)
#})

## Se sacan los flujos migratorios que pertencen a otros municipios
#tabla_municipios <- sapply(1:length(ZM_CF), function(i){
#                              p <- tabla1[[i]] %>%
#                                    as.data.frame() %>%
#                                     select(-c(`Otros estados`)) %>%
#                                      slice(-nrow(.))
#                              if(sum(p) == 0) {
#                                return(0)
#                              } else {
#                                p %>% 
#                                 adorn_totals(c("row", "col"), 
#                                                              fill = "-", 
#                                                               na.rm = TRUE, 
#                                                                ,,,,contains(colnames(tabla1[[i]]))) %>% 
#                                                  slice(nrow(.)) %>%
#                                                   mutate(Total = .$Total/100) %>%
#                                                    pull(Total)
#                              }
#                                           })


## Se guardan las matrices de movilidad estudiantil para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                              fill = "-", 
                              na.rm = TRUE, 
                              ,,,,contains(colnames(tabla1[[i]])))
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
}

saveRDS(tabla1, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))
total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio", 
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio", 
                                  Emigrantes = "%Entran por estudio") 

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Tabla MEst a nivel intermunicipal.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (Intermunicipal).pdf"

## Gráficos a nivel intermunicipal
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 9,
                    circos.axis.text = 6,
                    adj.text = c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZM a nivel intermunicipal.pdf"

## Etiquetas a nivel intermunicipal
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Gráfico Sankey

## Tomamos las Zonas Metropolitanas con más de 3 municipios con flujos migratorios 
ZM_CF <- ZM_2015 %>%
          group_by(CVE_ZM) %>%
           summarise(Count = n()) %>%
            filter(Count > 2) %>%
             pull(CVE_ZM)

tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>%
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character)
             
tabla1 <- lapply(1:length(ZM_CF), function(x){
                                   ZM <- ZM_2015 %>%
                                          select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                                           filter(CVE_ZM %in% ZM_CF[x])  %>%
                                            mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                                             pull(NOM_MUN)
                                    tabla %>%
                                     mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>%
                                      mutate(rn = case_when(.$rn %in% ZM ~ .$rn,
                                                            .$rn %nin% ZM ~ paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))])),
                                             cn = case_when(.$cn %in% ZM ~ .$cn,
                                                            .$cn %nin% ZM ~ paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]))) %>%
                                       filter(value > 0) 
  }
) 
p <- lapply(1:length(ZM_CF), function(x){
             tabla1[[x]] %>% 
              ggplot(aes(axis1 = rn, 
                          axis2 = cn, 
                           y = value),  # c("value", "freq", "tasa")
                      reverse = FALSE, 
                       na.rm = TRUE) +
               geom_alluvium(aes(fill = rn),
                              curve_type = "quintic", 
                               color = "transparent", 
                                alpha = 0.85, 
                                 lwd = 0.001, 
                                  width = 1/5,
                                   reverse = FALSE) +
                geom_stratum(aes(fill = cn), 
                              color = "white", 
                               alpha = 0.65,  
                                lwd = 0.001, 
                                 width = 1/5,
                                  reverse = FALSE) +
                  geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                                       fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                                   stat = "stratum", 
                                    size = 3, 
                                     direction = "y", 
                                      nudge_x = -.2,
                                       min.segment.length = unit(1, "lines"),
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                   geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                        fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                                    stat = "stratum", 
                                     size = 3,
                                      direction = "y", 
                                       nudge_x = .2, 
                                        force = 1,
                                         force_pull = 0,
                                          family = "montserrat",
                                           reverse = FALSE) +
                     theme_void() + 
                      theme(plot.margin = margin(t = 1, r = 1.5, b = 1, l = 0, "cm"),
                             text = element_text(family = "montserrat"),
                              axis.text = element_blank(),
                               axis.title = element_blank(),
                                strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                                 legend.key.size = unit(0.5, "cm"),
                                  legend.text = element_text(size = 9, family = "montserrat"),
                                   legend.position = c(1, .5)) + 
                       scale_x_discrete(expand = c(-0.1, 0.35)) +
                        scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                         guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                          labs(fill = "", 
                               color = "")
  }
)

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/GSankey de MEst desagregado por ZM_Absolutos (Intermunicipal).pdf")
ggexport(list = p, width = 14, height = 10, dpi = 400, filename = path)

ZMVM

ChordDiagram
ChorDiagram sin grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)   

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 500) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

################################################################################
tabla1 <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                            filtro_zm = ZM, 
                                            filtro_municipios = filtro, 
                                            filtro_estados = filtro_est, 
                                            category_group = estados, 
                                            category_names = nom_estados,
                                            group = "Otros estados") %>%
            dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%                        
            column_to_rownames(., var = "rn")     
# Paleta de colores
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM (Intermunicipal).pdf"

## Gráficos a nivel intermunicipal (ZMVM)
chord_diagram_graph(file = file, 
                    width = 7, 
                    height = 7, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0.25,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.1, 0.5),
                    adj.ylim = 0.2,
                    gap.degree = 3, 
                    clock.wise = FALSE,
                    track.margin = c(-0.2, 0.2),
                    margin = rep(1.5, 4))
ChordDiagram con grupos
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN %>% select(CVE_MUN, NOM_MUN)) %>%
                mutate(CVE_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = stringr::str_wrap(paste(.$CVE_MUN, .$NOM_MUN), 50)) %>% 
          pull(NOM_MUN)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)    

################################## Filtro ######################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             filter(rn %in% ZM) %>%
              mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
               filter(value > 500) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

################################################################################
tabla <- migration_flows_metropolitan_city(tabla = Migrantes, 
                                           filtro_zm = ZM, 
                                           filtro_municipios = filtro, 
                                           filtro_estados = filtro_est, 
                                           category_group = estados, 
                                           category_names = nom_estados,
                                           group = "Otros estados") 

tabla1 <- tabla %>%
           dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
            column_to_rownames(., var = "rn") 

# Grupo 1
grupo1 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "09") %>%
            pull(rn) %>%
             unique()
# Grupo 2
grupo2 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "15") %>%
            pull(rn) %>%
             unique()

# Grupo 3
grupo3 <- tabla %>%
           filter(substr(.$rn, 1, 2) == "13") %>%
            pull(rn) %>%
             unique()

# Grupo 4
grupo4 <- tabla %>%
           filter(substr(.$rn, 1, 2) %nin% c("09", "15", "13")) %>%
            pull(rn) %>%
             unique()

## Se guardan las matrices de movilidad laboral para analizarlos después. 
tabla <- tabla1 %>%
          as.data.frame() %>%
           adorn_totals(c("row", "col"),  
                         fill = "-", 
                         na.rm = TRUE, 
                         ,,,,contains(colnames(tabla1)))

wb <- createWorkbook()
addWorksheet(wb, "ZMVM")
writeData(wb, 1, tabla, colNames = TRUE, rowNames = TRUE)
saveWorkbook(wb, 
              file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst de ZMVM a nivel intermunicipal_Reduccion.xlsx"), 
               overwrite = TRUE)
# Paleta de colores
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = as.matrix(tabla1), paleta)

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst de ZMVM_grupos (Intermunicipal).pdf"

## Gráfico a nivel intermunicipal (ZMVM)
chord_diagram_graph_zmvm(file = file, 
                         width = 10, 
                         height = 10, 
                         family = "Montserrat Medium", 
                         paleta = paleta, 
                         tabla1 = as.matrix(tabla1), 
                         color_labels = "#000C7D",
                         transparency = 0.25,
                         circo.text = 9,
                         circos.axis.text = 7,
                         adj.text = c(-0.01, 0.5),
                         adj.ylim = 1,
                         gap.degree = 3, 
                         clock.wise = FALSE,
                         track.margin = c(-0.2, 0.2),
                         margin = rep(0, 4), 
                         group1 = grupo1, 
                         group1.text = "Ciudad de México",
                         group1.col = 1, 
                         group2 = grupo2, 
                         group2.text = "México",
                         group2.col = 15, 
                         group3 = grupo3, 
                         group3.text = "Hidalgo",
                         group3.col = 20, 
                         group4 = grupo4, 
                         group4.text = "Otro municipios",
                         group4.col = 30)

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZMVM a nivel intermunicipal.pdf"

## Etiquetas a nivel intermunicipal (ZMVM)
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 9, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1, 
                     labels = "ZM del Valle de México")
Gráfico Sankey

Zona Metropolitana del Valle de México (ZMVM)

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_MUN" = ".") %>%
               left_join(., MUN, by = c("CVE_MUN")) %>%
                mutate(CVE_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>%
                 pull(CVE_MUN)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

## Se toma como referencia a la Zona Metropolitana del Valle de México
ZM <- ZM_2015 %>% 
       select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
        filter(CVE_ZM %in% "09.01")  %>% 
         mutate(NOM_MUN = paste(.$CVE_MUN, .$NOM_MUN)) %>% 
          pull(NOM_MUN)

##########################################################################################
######################################## Filtro ##########################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)   

######################################## Filtro ##########################################
filtro  <- Inmigrantes %>%
            full_join(., Emigrantes, by = c("rn" = "cn")) %>%
             mutate(value = Inmigrantes + Emigrantes) %>%
              filter(rn %in% ZM) %>%
               filter(value > 30000) %>% 
                pull(rn)

filtro_est <- Inmigrantes %>%
               full_join(., Emigrantes, by = c("rn" = "cn")) %>%
                filter(rn %nin% ZM) %>%
                 mutate(value = sum_row(Inmigrantes, Emigrantes, na.rm = TRUE)) %>%
                  mutate(rn = substr(.$rn, 1, 3)) %>%
                   group_by(rn) %>%
                    summarise(value = sum(value)) %>%
                     filter(value > 500) %>%
                      pull(rn)

#########################################################################################
tabla <- Migrantes %>%
          as.data.frame() %>%
           tibble::rownames_to_column(var = "rn") %>% 
            melt(., id.vars = "rn", variable.name = "cn") %>%
             mutate_if(is.factor, as.character) %>%
              mutate(value = ifelse((.$rn != .$cn) & (.$rn %in% ZM | .$cn %in% ZM), value, 0)) %>% 
               mutate(rn = case_when(.$rn %in% ZM & .$rn %in% filtro  ~ .$rn,
                                     .$rn %in% ZM & .$rn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$rn, 1, 3))], "ZMVM"), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro & substr(.$rn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$rn, 1, 3))]), 20),
                                     .$rn %nin% ZM & .$rn %nin% filtro & substr(.$rn, 1, 3) %nin% filtro_est ~ "Otros estados"),
                       
                      cn = case_when(.$cn %in% ZM & .$cn %in% filtro  ~ .$cn,
                                     .$cn %in% ZM & .$cn %nin% filtro ~ str_wrap(paste(estados[as.numeric(substr(.$cn, 1, 3))], "ZMVM"), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro & substr(.$cn, 1, 3) %in% filtro_est ~ str_wrap(paste0(nom_estados[as.numeric(substr(.$cn, 1, 3))]), 20),
                                     .$cn %nin% ZM & .$cn %nin% filtro & substr(.$cn, 1, 3) %nin% filtro_est ~ "Otros estados")) %>%
                filter(value > 0) 


p <- tabla %>% 
      ggplot(aes(axis1 = rn, 
                  axis2 = cn, 
                   y = value),  # c("value", "freq", "tasa")
              reverse = FALSE, 
               na.rm = TRUE) +
       geom_alluvium(aes(fill = rn),
                      curve_type = "quintic", 
                       color = "transparent", 
                        alpha = 0.85,  
                         lwd = 0.001, 
                          width = 1/5,
                           reverse = FALSE) +
         geom_stratum(aes(fill = cn), 
                       color = "white", 
                        alpha = 0.65,  
                         lwd = 0.001, 
                          width = 1/5, 
                           reverse = FALSE) +
           geom_text_repel(aes(label = ifelse(after_stat(x) == 1, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""), 
                               fontface =  ifelse(after_stat(x) == 1, 'bold', 'plain')),
                            stat = "stratum", 
                             size = 3, 
                              direction = "y", 
                               nudge_x = -.23,
                                min.segment.length = unit(1, "lines"),
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
            geom_text_repel(aes(label = ifelse(after_stat(x)  == 2, paste0(as.character(after_stat(stratum)),  ": ", prettyNum(count, big.mark = " ")), ""),
                                fontface =  ifelse(after_stat(x) == 2, 'bold', 'plain')),
                             stat = "stratum", 
                              size = 3,
                               direction = "y", 
                                nudge_x = .23, 
                                 force = 1,
                                  force_pull = 0,
                                   family = "montserrat",
                                    reverse = FALSE) +
             theme_void() +  
              theme(plot.margin = margin(t = 1, r = 4, b = 1, l = 0, "cm"),
                     text = element_text(family = "montserrat"),
                      axis.text = element_blank(),
                       axis.title = element_blank(),
                        strip.text = element_text(size = 10, face = "bold", family = "montserrat"),
                         legend.key.size = unit(0.5, "cm"),
                          legend.text = element_text(size = 9, family = "montserrat"),
                           legend.position = c(0.999, .5)) + 
               scale_x_discrete(expand = c(-0.1, 0.5)) +
                scale_fill_viridis_d(option = "A", end = 0.9, begin = 0.2) +
                 guides(fill = guide_legend(ncol = 1, na.translate = F)) + 
                  labs(fill = "", 
                       color = "")

path = paste0(here::here(), "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/GSankey de MEst de la ZMVM (Intermunicipal).pdf")
ggexport(p, width = 20, height = 12, dpi = 400, filename = path)

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_MUN) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_MUN) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel intermunicipal 2015.RData"))

Residentes <- Migrantes %>%
               rownames_to_column() %>%
                gather(CVE_MUN, Value, -rowname)%>%
                 filter(rowname == CVE_MUN) %>%
                  select(-rowname) %>%
                   droplevels() %>%
                    rename("Residentes" = "Value") 

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- Migrantes %>% 
                as.data.frame() %>%
                 tibble::rownames_to_column(var = "CVE_MUN") %>%
                  melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                   mutate_at(vars(3), as.numeric) %>%
                    as_tibble() %>%
                     filter(CVE_MUN != CVE_MUN_ASI) %>%
                      group_by(CVE_MUN) %>%
                       summarise(Inmigrantes = sum(value, na.rm = TRUE))

################################################################################
############################### Emigrantes #####################################

## Población que entra a la entidad para estudiar v
Emigrantes <- Migrantes %>% 
               as.data.frame() %>%
                tibble::rownames_to_column(var = "CVE_MUN") %>%
                 melt(., id.vars = "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                  mutate_at(vars(3), as.numeric) %>%
                   as_tibble() %>%
                    filter(CVE_MUN != CVE_MUN_ASI) %>%
                     group_by(CVE_MUN_ASI) %>%
                      summarise(Emigrantes = sum(value, na.rm = TRUE)) %>%
                       rename("CVE_MUN" = "CVE_MUN_ASI") 

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_MUN")) %>%
          left_join(., Residentes, by = c("CVE_MUN")) %>%
          left_join(., Inmigrantes, by = c("CVE_MUN")) %>%
          left_join(., Emigrantes, by = c("CVE_MUN")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intermunicipal).xlsx"), overwrite = TRUE)

save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intermunicipal).RData"))

Movilidad metropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la Población de 3 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2015 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2015 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios) %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_metropolitana.RDS"))

Matrices

Se genera una matriz cruzada de la movilidad estudiantil a nivel municipal, utilizando la función svytable de la paquetería survey.

MC <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_metropolitana.RDS"))

Migrantes <- svytable(~CVE_ZM_ASI + CVE_ZM, design = MC)

Se genera la matriz cuadrada y se le asignan las etiquetas de municipios.

Migrantes <- Migrantes %>%
              as.data.frame() %>%
               expss::cross_cases(CVE_ZM, CVE_ZM_ASI, weight = Freq) %>%
                as.data.frame() %>%
                 rename("CVE_ZM" = "row_labels") %>% 
                  arrange(CVE_ZM) %>%
                   slice(-1) 
            
rownames <- Migrantes %>% 
             mutate(CVE_ZM = substr(.$CVE_ZM, 8, 12)) %>% 
              pull(CVE_ZM)

colnames <- names(Migrantes) %>% 
             as.data.frame() %>% 
              slice(-1) %>% 
               rename("CVE_ZM" = ".") %>%
                mutate(`CVE_ZM` = substr(.$CVE_ZM, 12, 17)) %>%
                 pull(CVE_ZM)

# Se elimina la variable CVE_ZM
Migrantes <- Migrantes %>%
              select(-CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

saveRDS(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2015.RDS"))
save(Migrantes, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2015.RData"))

require(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, "M.Metropolitano")
writeData(wb, 1, Migrantes %>% as.data.frame() %>% tibble::rownames_to_column(var = "CVE_ZM"), colNames = TRUE)
saveWorkbook(wb, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2015.xlsx"), overwrite = TRUE)

Matriz de Movilidad estudiantil a nivel municipal, 2015 - 2015

Matriz de movilidad estudiantil por zonas metropolitanas
Zonas Metropolitanas
CVE_ZM 01.01 02.01 02.02 02.03 03.01 04.01 05.01 05.02 05.03 05.04 06.01 06.02 07.01 07.02 08.01 08.02 08.03 08.04 09.01 10.01 11.01 11.02 11.03 11.04 11.05 12.01 12.02 13.01 13.02
01.01 307022 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 106 0 0 87 50 0 0 0 0 0 0
02.01 0 134903 115 59 0 2 0 0 0 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
02.02 0 104 272371 56 0 0 0 0 0 0 0 0 0 0 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0
02.03 0 289 117 498905 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0
03.01 0 6 2 0 73603 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
04.01 0 0 0 0 0 79728 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
05.01 0 0 0 0 0 0 363283 5 0 108 0 0 0 0 44 0 0 0 29 382 0 0 0 0 0 0 0 0 0
05.02 0 0 0 0 0 0 3 95181 16 175 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
05.03 0 0 0 0 0 0 0 6 47230 24 0 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 0
05.04 0 0 0 0 0 0 37 35 25 259196 0 0 0 0 0 0 0 0 27 0 0 0 0 0 0 0 0 0 0
06.01 0 0 0 0 0 0 0 0 0 0 99659 196 0 0 0 0 0 0 19 0 0 0 0 0 0 0 0 0 0
06.02 0 0 0 0 0 0 0 0 0 13 931 37669 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
07.01 0 0 0 0 0 0 0 0 0 0 0 0 98614 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
07.02 0 0 0 0 0 0 0 0 0 0 0 0 22 232659 0 0 0 0 16 0 0 8 0 0 0 0 0 0 0
08.01 0 0 1 0 0 0 66 0 0 0 0 0 0 0 267291 27 36 53 0 0 0 71 0 0 0 0 0 0 0
08.02 0 0 0 0 0 0 18 0 0 0 0 0 0 0 955 50214 30 27 0 0 0 0 0 0 0 0 0 0 0
08.03 0 0 0 0 0 0 16 0 0 0 0 0 0 0 249 0 31279 0 0 55 0 7 0 0 0 0 0 0 0
08.04 0 0 0 0 0 0 49 0 0 0 0 0 0 0 112 3 0 388631 0 0 0 0 0 0 0 0 0 0 0
09.01 0 36 0 5 0 42 15 0 0 2 86 12 31 17 33 0 0 44 5337558 24 25 32 8 0 0 268 21 3178 411
10.01 75 0 0 0 0 0 83 0 0 0 0 0 0 0 0 0 0 0 15 191744 0 9 1 0 0 0 0 0 0
11.01 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 207594 94 152 4 0 0 0 13 0
11.02 0 0 34 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 13 53875 801 0 0 0 0 0 0
11.03 0 0 0 0 7 0 0 0 0 10 0 0 0 0 17 0 0 0 0 0 94 1120 482419 0 193 0 0 0 0
11.04 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 63 62 33 27009 0 0 0 0 0
11.05 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 55 2079 0 47948 0 0 0 0
12.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 163 0 0 0 0 0 0 239641 372 0 0
12.02 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 71 0 0 0 0 0 0 387 98979 0 0
13.01 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1383 0 0 13 0 0 0 0 0 162537 23
13.02 8 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 1381 0 0 14 7 0 0 0 0 996 55562
13.03 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 202 0 0 0 0 3 0 0 0 1809 4
Fuente: Estimaciones del CONAPO.

Gráficos

ChordDiagram

Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2015 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2015 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
NOM_ZM <- stringr::str_wrap(nom_zm, 100)

################################################################################
tabla1 <- lapply(1, function(x){
                         Migrantes %>%
                          as.data.frame() %>%
                           tibble::rownames_to_column(var = "rn") %>% 
                            melt(., id.vars = "rn", variable.name = "cn") %>%
                             mutate_if(is.factor, as.character) %>%
                              mutate(value = ifelse((.$rn != .$cn), value, 0)) %>% 
                               filter(value > 0) %>%
                                dcast(., rn ~ cn, value.var = "value", sum,  na.rm = TRUE) %>%
                                 column_to_rownames(., var = "rn") 
}
)
# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (metropolitano).pdf"
 
## Gráficos a nivel metropolitano
chord_diagram_graph(file = file, 
                    width = 15, 
                    height = 10, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.05, 0.5), #Ajuste de las etiquetas (x, y)
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE,
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))
Gráficos por Zonas Metropolitanas

Se filtran los flujos migratorios que son exclusivos de los estados y que visualmente sean más interpretables.

load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel metropolitano 2015.RData"))

rownames <- rownames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2015 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

colnames <- colnames(Migrantes) %>% 
             as.data.frame() %>%
              rename("CVE_ZM" = ".") %>%
               left_join(., ZM_2015 %>% select(CVE_ZM, NOM_ZM) %>% distinct(CVE_ZM, NOM_ZM), by = c("CVE_ZM")) %>%
                mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
                 pull(CVE_ZM)

rownames(Migrantes) <- rownames
colnames(Migrantes) <- colnames

# Nombre de las Zonas Metropolitanas
ZM <- ZM_2015 %>% 
       select(CVE_ZM, NOM_ZM) %>% 
        distinct(CVE_ZM, NOM_ZM) %>%
         mutate(CVE_ZM = stringr::str_wrap(paste(.$CVE_ZM, .$NOM_ZM), 100)) %>%
          pull(CVE_ZM)

NOM_ZM_CF <- ZM_2015 %>%
              filter(CVE_ZM %in% ZM_CF) %>%
               distinct(CVE_ZM, NOM_ZM)

################################################################################
################################## Filtro ######################################
Inmigrantes <- Inmigrantes_function(ZM, Migrantes)

Emigrantes <- Emigrantes_function(ZM, Migrantes)

################################## Filtro ######################################
#p <- data.frame(ZM = ZM,
 #               filtro_zm = filtro_mig)
#write.xlsx(p, file = paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel metropolitano.xlsx"), overwrite = TRUE)

#### Filtro de municipios
filtro_mig <- read.xlsx(paste0(here::here(), "/Bases/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Filtro a nivel metropolitano.xlsx"), colNames = TRUE) %>%
               pull(filtro_zm)

################################################################################
tabla1 <- metropolitan_flows(tabla = Migrantes, 
                             filtro_zm = ZM, 
                             filtro_mig = filtro_mig, 
                             Emigrantes = Emigrantes, 
                             Inmigrantes = Inmigrantes, 
                             group = "Otras zonas metropolitanas")

## Se guardan las matrices de movilidad laboral para analizarlos después. 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     tabla <- tabla1[[i]] %>%
                as.data.frame() %>%
                 adorn_totals(c("row", "col"), 
                               fill = "-", 
                                na.rm = TRUE, 
          ,,,,contains(colnames(tabla1[[i]])))
                 
     addWorksheet(wb, zm[i])
     writeData(wb, i, tabla, colNames = TRUE, rowNames = TRUE)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano_Reduccion.xlsx"), 
               overwrite = TRUE)
}
saveRDS(tabla1, paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))
tabla1 <- readRDS(file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))

total_tablas <- totales(tabla1 = tabla1, 
                        Clave = "CVE_MUN", 
                        Inmigrantes = "Salen por estudio", 
                        Emigrantes = "Entran por estudio")

porcentajes_tablas <- porcentajes(tabla1 = tabla1, 
                                  Clave = "CVE_MUN", 
                                  Inmigrantes = "%Salen por estudio", 
                                  Emigrantes = "%Entran por estudio") 

# Se guardan los totales de las matrices reducidas 
wb <- createWorkbook()
for(i in 1:length(ZM)){
     addWorksheet(wb, paste(ZM_CF[i]))
     writeData(wb, i, total_tablas[[i]], colNames = TRUE, startCol = 1)
     writeData(wb, i, porcentajes_tablas[[i]], colNames = TRUE, startCol = 5)
     saveWorkbook(wb, 
                  file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst nivel intermunicipal_Reduccion_Totales.xlsx"), 
               overwrite = TRUE)
}
tabla1 <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz MEst a nivel metropolitano.RDS"))

# Paleta de colores
#paleta <- rev(colorRampPalette(wesanderson::wes_palette("Rushmore1"))(50)) 
paleta <- c("#000C7D", "#001599", "#0022B0", "#0035BB", "#004AB4", "#005EA3", "#00708D", "#078472","#3E9A85", "#49A980", "#58B877", "#70C669", "#94D25D", "#BBDA60", "#DDE379", "#DEE53E", "#DBCE33", "#D6B92A", "#D1A521", "#CA911A")

tabla2 <- color_chord_diagram(tabla1 = tabla1, paleta)
file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/ChordDiagram de MEst desagregado por ZM (metropolitano)_individual.pdf"
 
## Gráficos a nivel metropolitano
chord_diagram_graph(file = file, 
                    width = 8, 
                    height = 8, 
                    family = "Montserrat Medium", 
                    paleta = paleta, 
                    tabla1 = tabla1, 
                    tabla2 = tabla2, 
                    color_labels = "#000C7D",
                    transparency = 0,
                    circo.text = 7,
                    circos.axis.text = 5,
                    adj.text = c(-0.15, 0.5),
                    adj.ylim = 0.1,
                    gap.degree = 2, 
                    clock.wise = FALSE, 
                    track.margin = c(-0.07, 0.1),
                    margin = rep(0, 4))

Etiquetas

file = "/Graficos/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Etiquetas ZM a nivel metropolitano.pdf"

## Etiquetas a nivel zona metropolitana
labels_chord_diagram(file = file, 
                     width = 7, 
                     height = 8, 
                     family = "Montserrat Medium", 
                     paleta = paleta, 
                     tabla1 = tabla1,
                     labels = paste(NOM_ZM_CF[,1], NOM_ZM_CF[,2]))

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de Movilidad estudiantil a nivel municipal 2015.RData"))

ZM <- lapply(1:length(zm), function(x){
                 ZM_2015 %>% 
                  select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                   filter(CVE_ZM %in% zm[x])  %>% 
                    pull(CVE_MUN)
})

Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
  })

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de trabajo
Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################

# Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudio
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Metropolitano) 2015.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Metropolitano) 2015.RData"))
Indicadores de movilidad estudiantil a nivel metropolitano
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 930 969 875 180 296 647 12 764 16 679 −3 915 29 443 2.8e+00 3.7e+00 −0.9 −33 358
02.01 1 730 591 1 630 504 134 903 249 674 −425 923 3.0e-02 8.0e-02 −0.1 −1 348
03.01 932 001 882 638 73 603 147 441 −294 588 3.2e-02 9.7e-02 −0.1 −882
04.01 1 214 931 1 145 236 79 728 695 2 811 −2 116 3 506 1.2e-01 4.8e-01 −0.4 −5 622
05.01 820 838 772 694 341 757 23 081 25 204 −2 123 48 285 5.8e+00 6.3e+00 −0.5 −50 408
06.01 316 334 297 624 81 654 19 181 20 705 −1 524 39 886 1.2e+01 1.3e+01 −1.0 −41 410
07.01 178 886 167 979 98 614 631 6 414 −5 783 7 045 7.3e-01 7.4e+00 −6.7 −12 828
08.01 330 435 313 745 265 461 2 256 5 710 −3 454 7 966 1.4e+00 3.5e+00 −2.1 −11 420
09.01 141 869 132 224 4 227 810 1 140 598 1 126 019 14 579 2 266 617 1.7e+03 1.6e+03 21.3 −2 252 038
10.01 683 404 644 353 191 744 862 2 882 −2 020 3 744 2.6e-01 8.7e-01 −0.6 −5 764
11.01 1 328 246 1 248 795 203 135 6 612 12 445 −5 833 19 057 1.0e+00 1.9e+00 −0.9 −24 890
12.01 847 021 806 338 238 067 3 054 3 782 −728 6 836 7.4e-01 9.1e-01 −0.2 −7 564
13.01 20 014 450 19 066 889 135 632 31 400 45 244 −13 844 76 644 3.2e-01 4.6e-01 −0.1 −90 488
14.01 1 604 170 1 506 066 1 190 098 184 654 194 740 −10 086 379 394 2.4e+01 2.5e+01 −1.3 −389 480
15.01 183 266 171 180 38 111 10 422 26 386 −15 964 36 808 1.2e+01 3.0e+01 −18.0 −52 772
16.01 110 797 105 767 60 970 3 284 3 446 −162 6 730 6.1e+00 6.4e+00 −0.3 −6 892
17.01 859 676 811 968 108 334 20 421 16 615 3 806 37 036 4.9e+00 4.0e+00 0.9 −33 230
18.01 515 075 488 068 135 282 8 621 14 323 −5 702 22 944 3.4e+00 5.7e+00 −2.3 −28 646
19.01 242 261 228 605 990 241 244 650 248 300 −3 650 492 950 2.1e+02 2.1e+02 −3.1 −496 600
20.01 205 954 194 289 139 021 51 879 63 434 −11 555 115 313 5.2e+01 6.3e+01 −11.5 −126 868
Fuente: Estimaciones del CONAPO.

Migración intrametropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2015 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2015 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a estudiar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "Pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_intrametropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
MR <- readRDS(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matrices de MEst a nivel intramunicipal por ZM2015.RDS"))

Residentes <- lapply(1:length(zm), function(x){
                                     MR[[x]] %>% 
                                      as.data.frame() %>%
                                       melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                        mutate_at(vars(3), as.numeric) %>%
                                         filter(CVE_MUN == CVE_MUN_ASI)  %>%
                                          summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                           mutate(CVE_ZM = !!paste0(zm[x])) 
})

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- lapply(1:length(zm), function(x){
                                      MR[[x]] %>% 
                                       as.data.frame() %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                            mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################

# Población que entra a la entidad para estudiar
Emigrantes <- lapply(1:length(zm), function(x){
                                    MR[[x]] %>% 
                                     tibble::column_to_rownames(var = "CVE_MUN") %>%
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                            summarize(Emigrantes=  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intrametropolitano) 2015.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intrametropolitano) 2015.RData"))
Indicadores de movilidad estudiantil a nivel intrametropolitano
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 930 969 875 180 296 647 10 375 10 375 0 20 750 2.298 2.298 0.0 −20 750
02.01 1 730 591 1 630 504 272 371 0 0 0 0 0.000 0.000 0.0 0
03.01 932 001 882 638 134 903 0 0 0 0 0.000 0.000 0.0 0
04.01 1 214 931 1 145 236 79 728 0 0 0 0 0.000 0.000 0.0 0
05.01 820 838 772 694 493 346 5 559 5 559 0 11 118 1.395 1.395 0.0 −11 118
06.01 316 334 297 624 73 603 0 0 0 0 0.000 0.000 0.0 0
07.01 178 886 167 979 252 269 6 927 6 927 0 13 854 7.988 7.988 0.0 −13 854
08.01 330 435 313 745 341 757 21 526 21 526 0 43 052 13.366 13.366 0.0 −43 052
09.01 141 869 132 224 89 643 5 538 5 538 0 11 076 8.082 8.082 0.0 −11 076
10.01 683 404 644 353 46 464 766 766 0 1 532 0.231 0.231 0.0 −1 532
11.01 1 328 246 1 248 795 81 654 18 005 18 005 0 36 010 2.795 2.795 0.0 −36 010
12.01 847 021 806 338 37 276 393 393 0 786 0.095 0.095 0.0 −786
13.01 20 014 450 19 066 889 223 219 9 440 9 440 0 18 880 0.097 0.097 0.0 −18 880
14.01 1 604 170 1 506 066 265 461 1 830 1 830 0 3 660 0.235 0.235 0.0 −3 660
15.01 183 266 171 180 388 631 0 0 0 0 0.000 0.000 0.0 0
16.01 110 797 105 767 48 927 1 287 1 287 0 2 574 2.377 2.377 0.0 −2 574
17.01 859 676 811 968 4 227 810 1 109 748 1 109 748 0 2 219 496 265.546 265.546 0.0 −2 219 496
18.01 515 075 488 068 203 135 4 459 4 459 0 8 918 1.778 1.778 0.0 −8 918
19.01 242 261 228 605 341 786 27 051 27 051 0 54 102 22.980 22.980 0.0 −54 102
20.01 205 954 194 289 191 744 0 0 0 0 0.000 0.000 0.0 0
Fuente: Estimaciones del CONAPO.

Migración intermetropolitana

Se utiliza la paquetería survey para poder trabajar con la muestra del cuestionario ampliado, en la cual se selecciona a la población de 5 años y más.

options(survey.lonely.psu = "adjust")

MC <- mydata %>%
      select(CVE_ENT, NOM_ENT, MUN, CVE_MUN, NOM_MUN, ENT_PAIS_ASI, MUN_ASI, CVE_MUN_ASI,
             EDAD, CVE_ZM, NOM_ZM, CVE_ZM_ASI, ZM_ASI, FACTOR, ESTRATO, UPM) %>%
        # Se genera una indicadora de zm 
        mutate(I_ZM_2015 = ifelse(is.na(.$CVE_ZM), '0', '1'),
               I_ASI_ZM_2015 = ifelse(is.na(.$CVE_ZM_ASI), '0', '1')) %>%
        # Se clasifican a los migrantes internos 
        mutate(I_ZM = case_when(.$CVE_MUN == .$CVE_MUN_ASI ~ 'Pertenecen a la Zona Metropolitana', #Estudian en el mismo municipio
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM == .$CVE_ZM_ASI ~ "Pertenecen a la Zona Metropolitana", #Estudian en otro municipio dentro de la misma zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '1' & .$CVE_ZM != .$CVE_ZM_ASI ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio pero de otra zona metropolitana
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '1' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana', #Estudian en otro municipio que no pertenece a la zona metropolitana pero viven en una ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '1' ~ 'No pertenecen a la Zona Metropolitana', #Entran a trabajar a la zona metropolitana pero no pertecen a la ZM
                                .$CVE_MUN != .$CVE_MUN_ASI & .$I_ZM_2015 %in% '0' & .$I_ASI_ZM_2015 %in% '0' ~ 'No pertenecen a la Zona Metropolitana' #Estudian en otro municipio que no es ZM y no residen en una ZM
                                ))  %>%
         filter((EDAD >= 3 & EDAD <= 130)) %>%
          filter(CVE_MUN_ASI %in% municipios & .$I_ZM %in% "No pertenecen a la Zona Metropolitana") %>%
           svydesign(data = ., id = ~ UPM, strata = ~ESTRATO, weight = ~FACTOR, nest = T)

saveRDS(MC, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/MC_intermetropolitana.RDS"))

Indicadores

Se realizan cálculos generales de migración:

  • Residentes

  • Inmigrantes

  • Emigrantes

  • % Inmigrantes

  • % Emigrante

  • Migración bruta

  • Migración Neta

  • % Tasa de migración bruta

  • % Tasa de migración neta

Se trabaja con la matriz cuadrada, la cual de esta manera no se satura la computadora.

################################################################################
############################ Población total ###################################
Pob.Total <- mydata %>%
              as.data.frame() %>%
               group_by(CVE_ZM) %>%
                summarise(Pob.Total = sum(FACTOR)) 

################################################################################
###################### Población de 3 años y más ###############################
Pob.3ymas <- mydata %>%
              as.data.frame() %>%
               mutate(EDAD = as.numeric(.$EDAD)) %>%
                subset(EDAD >= 3 & EDAD <=130) %>%
                 group_by(CVE_ZM) %>%
                  summarise(Pob.3ymas = sum(FACTOR)) 

################################################################################
########################### Residentes #########################################
load(paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Matriz de movilidad estudiantil a nivel intermunicipal 2015.RData"))

ZM <- lapply(1:length(zm), function(x){
                    ZM_2015 %>% 
                     select(CVE_ZM, CVE_MUN, NOM_MUN) %>%
                      filter(CVE_ZM %in% zm[x])  %>% 
                       pull(CVE_MUN)
})

Residentes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN == CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Residentes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Residentes <- do.call(rbind.data.frame, Residentes)

################################################################################
############################### Inmigrantes ####################################

## Población que sale de su entidad de residencia y entra a otra demarcación por motivos de estudios
Inmigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      as.data.frame() %>%
                                       tibble::rownames_to_column(var = "CVE_MUN") %>%
                                        melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                         mutate_at(vars(3), as.numeric) %>%
                                          filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Inmigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Inmigrantes <- do.call(rbind.data.frame, Inmigrantes)

################################################################################
############################### Emigrantes #####################################

# Población que entra a la entidad para estudiar
Emigrantes <- lapply(1:length(zm), function(x){
                                     Migrantes %>% 
                                      t() %>%
                                       as.data.frame() %>%
                                        tibble::rownames_to_column(var = "CVE_MUN") %>%
                                         melt(., id.vars =  "CVE_MUN", variable.name = "CVE_MUN_ASI") %>%
                                          mutate_at(vars(3), as.numeric) %>%
                                           filter(CVE_MUN != CVE_MUN_ASI)  %>%
                                           filter(CVE_MUN %in% ZM[[x]]) %>%
                                            summarize(Emigrantes =  sum(value, na.rm = TRUE)) %>% 
                                             mutate(CVE_ZM = !!paste0(zm[x])) 
})

Emigrantes <- do.call(rbind.data.frame, Emigrantes)

tabla <- Pob.Total %>%
          left_join(., Pob.3ymas, by = c("CVE_ZM")) %>%
          left_join(., Residentes, by = c("CVE_ZM")) %>%
          left_join(., Inmigrantes, by = c("CVE_ZM")) %>%
          left_join(., Emigrantes, by = c("CVE_ZM")) %>%
           mutate(Mig.Neta = .$Inmigrantes - .$Emigrantes,
                  Mig.Bruta = .$Inmigrantes + .$Emigrantes, 
                  Tasa.Inmig = ((.$Inmigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Emig = ((.$Emigrantes/ 5) /((.$Pob.Total + .$Pob.3ymas) / 2)) * 1000,
                  Tasa.Mig = Tasa.Inmig - Tasa.Emig, 
                  Eficacia = Mig.Neta - Mig.Bruta)

write.xlsx(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intermetropolitano) 2015.xlsx"), overwrite = TRUE)
save(tabla, file = paste0(here::here(), "/Output/Municipio/06_Zonas Metropolitanas/2015/04_Movilidad estudiantil/Indicadores de MEst por ZM 2015 (Intermetropolitano) 2015.RData"))
Indicadores de movilidad estudiantil a nivel intermetropolitano
Zonas Metropolitanas
CVE_ZM Pob.Total Pob.3ymas Residentes Inmigrantes Emigrantes Mig.Neta Mig.Bruta Tasa.Inmig Tasa.Emig Tasa.Mig Eficacia
01.01 930 969 875 180 0 2 389 6 304 −3 915 8 693 0.529 1.396 −0.9 −12 608
02.01 1 730 591 1 630 504 0 249 674 −425 923 0.030 0.080 −0.1 −1 348
03.01 932 001 882 638 0 147 441 −294 588 0.032 0.097 −0.1 −882
04.01 1 214 931 1 145 236 0 695 2 811 −2 116 3 506 0.118 0.476 −0.4 −5 622
05.01 820 838 772 694 0 1 555 3 678 −2 123 5 233 0.390 0.923 −0.5 −7 356
06.01 316 334 297 624 0 1 176 2 700 −1 524 3 876 0.766 1.759 −1.0 −5 400
07.01 178 886 167 979 0 631 6 414 −5 783 7 045 0.728 7.397 −6.7 −12 828
08.01 330 435 313 745 0 426 3 880 −3 454 4 306 0.265 2.409 −2.1 −7 760
09.01 141 869 132 224 0 30 850 16 271 14 579 47 121 45.021 23.745 21.3 −32 542
10.01 683 404 644 353 0 862 2 882 −2 020 3 744 0.260 0.868 −0.6 −5 764
11.01 1 328 246 1 248 795 0 2 153 7 986 −5 833 10 139 0.334 1.240 −0.9 −15 972
12.01 847 021 806 338 0 1 480 2 208 −728 3 688 0.358 0.534 −0.2 −4 416
13.01 20 014 450 19 066 889 0 4 495 18 339 −13 844 22 834 0.046 0.188 −0.1 −36 678
14.01 1 604 170 1 506 066 0 3 637 13 723 −10 086 17 360 0.468 1.765 −1.3 −27 446
15.01 183 266 171 180 0 4 601 20 565 −15 964 25 166 5.192 23.208 −18.0 −41 130
16.01 110 797 105 767 0 1 104 1 266 −162 2 370 2.039 2.338 −0.3 −2 532
17.01 859 676 811 968 0 8 319 4 513 3 806 12 832 1.991 1.080 0.9 −9 026
18.01 515 075 488 068 0 638 6 340 −5 702 6 978 0.254 2.528 −2.3 −12 680
19.01 242 261 228 605 0 1 252 4 902 −3 650 6 154 1.064 4.164 −3.1 −9 804
20.01 205 954 194 289 0 5 611 17 166 −11 555 22 777 5.608 17.156 −11.5 −34 332
Fuente: Estimaciones del CONAPO.

Referencias

Librerias que se usaron en el documento

package loadedversion source
Cairo 1.6-1 CRAN (R 4.3.1)
chorddiag 0.1.3 Github ()
circlize 0.4.15 CRAN (R 4.3.1)
doMC 1.3.5 R-Forge (R 4.3.1)
dplyr 1.1.3 CRAN (R 4.3.2)
expss 0.11.6 CRAN (R 4.3.1)
foreach 1.5.2 CRAN (R 4.3.1)
ggalluvial 0.12.5 CRAN (R 4.3.1)
ggplot2 3.4.3 CRAN (R 4.3.1)
ggpubr 0.6.0 CRAN (R 4.3.1)
ggrepel 0.9.3 CRAN (R 4.3.1)
ggsankey 0.0.99999 Github ()
gt 0.10.0 CRAN (R 4.3.1)
haven 2.5.3 CRAN (R 4.3.1)
Hmisc 5.1-0 CRAN (R 4.3.1)
iterators 1.0.14 CRAN (R 4.3.1)
janitor 2.2.0 CRAN (R 4.3.1)
kableExtra 1.3.4 CRAN (R 4.3.1)
knitr 1.45 CRAN (R 4.3.2)
maditr 0.8.3 CRAN (R 4.3.1)
Matrix 1.6-1.1 CRAN (R 4.3.1)
network 1.18.1 CRAN (R 4.3.1)
openxlsx 4.2.5.2 CRAN (R 4.3.1)
reshape2 1.4.4 CRAN (R 4.3.1)
sjlabelled 1.2.0 CRAN (R 4.3.1)
sna 2.7-1 CRAN (R 4.3.1)
srvyr 1.2.0 CRAN (R 4.3.1)
statnet.common 4.9.0 CRAN (R 4.3.1)
stringr 1.5.0 CRAN (R 4.3.1)
survey 4.2 Github ()
survival 3.5-5 CRAN (R 4.3.1)
tibble 3.2.1 CRAN (R 4.3.1)
tidyr 1.3.0 CRAN (R 4.3.1)

Creative Commons Licence
This work by Diana Villasana Ocampo is licensed under a Creative Commons Attribution 4.0 International License.